package com.heima.kafka.simple;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者类对象
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //2.添加配置信息
        Properties properties=new Properties();
        //连接kafka信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.229.142:9092");
        //对key进行字符串序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //对value进行字符串序列化
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //设置重试的次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        //1.获取生产者对象
        KafkaProducer<String,String>kafkaProducer=new KafkaProducer(properties);
        /**
         * 3.发送消息内容
         * ProducerRecord(String topic, K key, V value)
         * 参数1 表示当前消息的队列主题
         * 参数2表示消息的key
         * 参数3表示消息的value
         */

        for (int i = 0; i <5 ; i++) {
            if(i%2==0){
                ProducerRecord<String, String> record=new ProducerRecord<String,String>("kafkastream-topic1","first"+i,"hello kafka");
                kafkaProducer.send(record);
            }else{
                ProducerRecord<String, String> record=new ProducerRecord<String,String>("kafkastream-topic1","first"+i,"hello itcast");
                kafkaProducer.send(record);
            }

        }


        /**
         * 同步发送
         */
//        Future<RecordMetadata> future = kafkaProducer.send(record);
//        RecordMetadata metadata = future.get();
//        System.out.println(metadata.offset());
        /**
         * 异步发送
         */
//        kafkaProducer.send(record, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata metadata, Exception exception) {
//                //表示有异常
//                if(exception!=null){
//                    //继续重试发送或者给抱一个错误
//                    throw new RuntimeException(exception);
//                }
//                //没有异常
//                System.out.println(metadata.offset());
//            }
//        });

        //4.关闭流
        kafkaProducer.close();
    }
}
